package cn.hebutrun.oulabot.common.config;

import cn.hutool.core.date.DatePattern;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.io.IOException;
import java.math.BigInteger;
import java.time.ZoneId;
import java.util.Locale;
import java.util.TimeZone;

/**
 * Jackson配置类
 *
 * @author meng ran
 * @since 2018-10-31 09:01
 */
@Configuration
@ConditionalOnClass(ObjectMapper.class)
@AutoConfigureBefore(JacksonAutoConfiguration.class)
public class JacksonConfig {

  /**
   * 解决前端js处理大数字丢失精度问题，将Long和BigInteger转换成string.
   *
   * <p>console.log(812782555915911412) ; => 812782555915911400
   *
   * <p>Jackson全局转化long类型为String，解决jackson序列化时long类型缺失精度问题
   *
   * <p>
   *
   * <p>LocalDateTime 序列化
   */
  @Bean
  @Primary
  public Jackson2ObjectMapperBuilderCustomizer customizer() {
    return builder -> {
      builder.locale(Locale.CHINA);
      builder.timeZone(TimeZone.getTimeZone(ZoneId.systemDefault()));
      builder.simpleDateFormat(DatePattern.NORM_DATETIME_PATTERN);
      builder.modules(new JavaTimeModule());
      builder
          .serializerByType(Long.class, ToStringSerializer.instance)
          .serializerByType(Long.TYPE, ToStringSerializer.instance)
          .serializerByType(BigInteger.class, ToStringSerializer.instance);
    };
  }

  /** null转换为空字符串 */
  @Bean
  @Primary
  public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
    ObjectMapper objectMapper = builder.createXmlMapper(false).build();
    objectMapper
        .getSerializerProvider()
        .setNullValueSerializer(
            new JsonSerializer<>() {
              @Override
              public void serialize(Object o, JsonGenerator jg, SerializerProvider sp)
                  throws IOException {
                // Converts null to an empty string when the Spring boot interface returns JSON
                jg.writeString("");
              }
            });

    return objectMapper;
  }
}
